package com.admin.service.ipl;

import com.admin.fen.BehaviorFeign;
import com.admin.mapper.SearchMapper;
import com.admin.service.SearchService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.usian.model.atri.pojos.ApArticle;
import com.usian.model.behavior.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.es.ApUserSearch;
import com.usian.model.es.UserSearchDto;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, ApUserSearch> implements SearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Override
    public ResponseResult matchQuery(UserSearchDto dto) throws IOException {
        if (dto==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
       // Integer userId = AppThreadLocalUtils.getUser().getId();

        SearchRequest request = new SearchRequest("app_info_article");
        request.source().query(QueryBuilders.matchQuery("title",dto.getSearchWords()));
        request.source().from((dto.getPageNum()-1)*dto.getPageSize()).size(dto.getPageSize());
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        ApBehaviorEntry behaviorEntry = behaviorFeign.findBehavior(4);
        insert(behaviorEntry.getId(),dto.getSearchWords());
         return ResponseResult.okResult(responseHandle(response));
    }



   //异步 定义添加方法
    @Async("taskExecutor")
    public void insert(Integer entryId,String searchWords){
        ApUserSearch apUserSearch = getOne(Wrappers.<ApUserSearch>lambdaQuery().eq(ApUserSearch::getEntryId, entryId).eq(ApUserSearch::getKeyword, searchWords));
        if (apUserSearch!=null&&apUserSearch.getStatus()==1){

        }else if (apUserSearch!=null&&apUserSearch.getStatus()==0){
            apUserSearch.setStatus(1);
            updateById(apUserSearch);
        }

        //不存在情况 添加数据
        ApUserSearch search = new ApUserSearch();
        search.setStatus(1);
        search.setCreatedTime(new Date());
        search.setEntryId(entryId);
        search.setKeyword(searchWords);
        save(search);

    }




    public List<ApArticle> responseHandle(SearchResponse response){
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        List<ApArticle> list=new ArrayList<>();
        for (SearchHit hit:hits1) {
            String sourceAsString = hit.getSourceAsString();
            ApArticle apArticle = JSON.parseObject(sourceAsString, ApArticle.class);
            list.add(apArticle);
            System.out.println(apArticle);
        }
        return list;
    }

}
